#!/usr/bin/env python3
"""
Bash执行器功能测试
测试Bash语言的基本执行功能，不涉及安全和系统资源测试
"""

import asyncio
import sys
import os
sys.path.append(os.path.dirname(os.path.abspath(__file__)))
from base_test import BaseCodeSandboxTest

class TestBashExecutor(BaseCodeSandboxTest):
    """Bash代码执行器测试类"""
    
    def __init__(self):
        super().__init__()
        self.code_type = "bash"
    
    async def test_basic_functionality(self):
        """测试Bash基础功能"""
        print("🐚 测试Bash基础功能...")
        
        test_cases = [
            {
                "name": "简单输出",
                "code": "echo 'Hello Bash!'",
                "security_level": "low",
                "timeout_seconds": 10,
                "expected_output": ["Hello Bash!"]
            },
            {
                "name": "变量操作",
                "code": '''NAME="World"
echo "Hello $NAME!"''',
                "security_level": "low",
                "timeout_seconds": 10,
                "expected_output": ["Hello World!"]
            },
            {
                "name": "数学计算",
                "code": '''A=5
B=3
RESULT=$((A + B))
echo "计算结果: $RESULT"''',
                "security_level": "low",
                "timeout_seconds": 10,
                "expected_output": ["计算结果: 8"]
            },
            {
                "name": "条件判断",
                "code": '''NUM=10
if [ $NUM -gt 5 ]; then
    echo "数字大于5"
else
    echo "数字不大于5"
fi''',
                "security_level": "low",
                "timeout_seconds": 10,
                "expected_output": ["数字大于5"]
            }
        ]
        
        for case in test_cases:
            await self.run_test_case(case)
    
    async def test_control_structures(self):
        """测试Bash控制结构"""
        print("🔄 测试Bash控制结构...")
        
        test_cases = [
            {
                "name": "for循环",
                "code": '''echo "循环开始:"
for i in 1 2 3; do
    echo "循环 $i"
done
echo "循环结束"''',
                "security_level": "low",
                "timeout_seconds": 10,
                "expected_output": ["循环开始:", "循环 1", "循环 2", "循环 3", "循环结束"]
            },
            {
                "name": "while循环",
                "code": '''COUNTER=1
echo "while循环:"
while [ $COUNTER -le 3 ]; do
    echo "计数: $COUNTER"
    COUNTER=$((COUNTER + 1))
done''',
                "security_level": "low",
                "timeout_seconds": 10,
                "expected_output": ["while循环:", "计数: 1", "计数: 2", "计数: 3"]
            }
        ]
        
        for case in test_cases:
            await self.run_test_case(case)
    
    async def test_advanced_features(self):
        """测试Bash高级功能"""
        print("🔧 测试Bash高级功能...")
        
        test_cases = [
            {
                "name": "字符串处理",
                "code": '''TEXT="Hello World"
echo "原文: $TEXT"
echo "长度: ${#TEXT}"''',
                "security_level": "low",
                "timeout_seconds": 10,
                "expected_output": ["原文: Hello World", "长度: 11"]
            },
            {
                "name": "数组操作",
                "code": '''FRUITS=("apple" "banana" "orange")
echo "水果数组:"
for fruit in "${FRUITS[@]}"; do
    echo "- $fruit"
done
echo "数组长度: ${#FRUITS[@]}"''',
                "security_level": "low",
                "timeout_seconds": 10,
                "expected_output": ["水果数组:", "- apple", "- banana", "- orange", "数组长度: 3"]
            },
            {
                "name": "函数定义和调用",
                "code": '''greet() {
    local name=$1
    echo "Hello, $name!"
}

echo "函数测试:"
greet "Alice"
greet "Bob"''',
                "security_level": "low",
                "timeout_seconds": 10,
                "expected_output": ["函数测试:", "Hello, Alice!", "Hello, Bob!"]
            }
        ]
        
        for case in test_cases:
            await self.run_test_case(case)
    
    async def test_system_interaction(self):
        """测试Bash系统交互"""
        print("⚙️ 测试Bash系统交互...")
        
        test_cases = [
            {
                "name": "基本命令",
                "code": '''echo "当前时间:"
date '+%Y-%m-%d'
echo "环境变量测试:"
echo "PATH长度: ${#PATH}"''',
                "security_level": "low",
                "timeout_seconds": 10,
                "expected_output": ["当前时间:", "环境变量测试:", "PATH长度:"]
            },
            {
                "name": "管道和重定向",
                "code": '''echo "测试管道:"
echo -e "line1\\nline2\\nline3" | grep "line2"
echo "测试排序:"
echo -e "c\\na\\nb" | sort''',
                "security_level": "low",
                "timeout_seconds": 10,
                "expected_output": ["测试管道:", "line2", "测试排序:", "a"]
            },
            {
                "name": "退出状态码",
                "code": '''echo "测试退出状态:"
true
echo "true命令状态: $?"
false
echo "false命令状态: $?"''',
                "security_level": "low",
                "timeout_seconds": 10,
                "expected_output": ["测试退出状态:", "true命令状态: 0", "false命令状态: 1"]
            }
        ]
        
        for case in test_cases:
            await self.run_test_case(case)
    
    async def run_all_tests(self):
        """运行所有Bash测试"""
        print("🚀 开始Bash代码执行器完整测试...")
        
        try:
            await self.test_basic_functionality()
            await self.test_control_structures()
            await self.test_advanced_features()
            await self.test_system_interaction()
            
            print("✅ Bash测试全部完成!")
            return True
            
        except Exception as e:
            print(f"❌ Bash测试失败: {e}")
            return False

async def main():
    """主函数"""
    async with TestBashExecutor() as tester:
        success = await tester.run_all_tests()
        tester.print_test_summary()
    return success

if __name__ == "__main__":
    success = asyncio.run(main())
    exit(0 if success else 1) 